package com.example.hrsystem.ui.task;

import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.ViewModelProvider;

import com.example.hrsystem.R;
import com.example.hrsystem.data.model.TaskItem;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

/**
 * 任务详情界面Activity
 * 显示任务的详细信息，并提供更新任务状态的功能
 */
public class TaskDetailActivity extends AppCompatActivity {

    private TaskViewModel taskViewModel;
    private TextView titleTextView;
    private TextView contentTextView;
    private TextView taskTypeTextView;
    private TextView statusTextView;
    private TextView priorityTextView;
    private TextView createTimeTextView;
    private TextView deadlineTextView;
    private TextView creatorTextView;
    private TextView assigneeTextView;
    private TextView remarkTextView;
    private TextView attachmentTextView;
    private View updateStatusContainer;
    private SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
    private int taskId;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_task_detail);

        // 初始化UI组件
        initUI();

        // 获取任务ID
        if (getIntent().hasExtra("taskId")) {
            taskId = getIntent().getIntExtra("taskId", -1);
        } else {
            taskId = -1;
        }

        // 检查任务ID是否有效
        if (taskId == -1) {
            Toast.makeText(this, "无效的任务ID", Toast.LENGTH_SHORT).show();
            finish();
            return;
        }

        // 初始化ViewModel
        taskViewModel = new ViewModelProvider(this).get(TaskViewModel.class);

        // 观察加载状态
        taskViewModel.getIsLoading().observe(this, isLoading -> {
            // 可以在这里显示加载指示器
        });

        // 观察错误信息
        taskViewModel.getErrorMessage().observe(this, errorMessage -> {
            if (errorMessage != null && !errorMessage.isEmpty()) {
                Toast.makeText(this, errorMessage, Toast.LENGTH_SHORT).show();
            }
        });

        // 观察任务详情
        observeTaskDetail();

        // 设置更新状态按钮点击事件
        findViewById(R.id.update_status_button).setOnClickListener(v -> {
            // 根据当前状态设置新状态
            String currentStatus = statusTextView.getText().toString();
            String newStatus = "未开始";
            if ("未开始".equals(currentStatus)) {
                newStatus = "进行中";
            } else if ("进行中".equals(currentStatus)) {
                newStatus = "已完成";
            }
            taskViewModel.updateTaskStatus(taskId, newStatus);
        });

        // 设置返回按钮点击事件
        findViewById(R.id.back_button).setOnClickListener(v -> finish());
    }

    /**
     * 初始化UI组件
     */
    private void initUI() {
        titleTextView = findViewById(R.id.task_title_text_view);
        contentTextView = findViewById(R.id.task_content_text_view);
        taskTypeTextView = findViewById(R.id.task_type_text_view);
        statusTextView = findViewById(R.id.task_status_text_view);
        priorityTextView = findViewById(R.id.task_priority_text_view);
        createTimeTextView = findViewById(R.id.create_time_text_view);
        deadlineTextView = findViewById(R.id.deadline_text_view);
        creatorTextView = findViewById(R.id.creator_text_view);
        assigneeTextView = findViewById(R.id.assignee_text_view);
        remarkTextView = findViewById(R.id.remark_text_view);
        attachmentTextView = findViewById(R.id.attachment_text_view);
        updateStatusContainer = findViewById(R.id.update_status_container);
    }

    /**
     * 观察任务详情
     */
    private void observeTaskDetail() {
        if (taskId != -1) {
            taskViewModel.getTaskById(taskId).observe(this, task -> {
                if (task != null) {
                    updateTaskDetailUI(task);
                } else {
                    Toast.makeText(this, "未找到任务详情", Toast.LENGTH_SHORT).show();
                }
            });
        } else {
            Toast.makeText(this, "任务ID无效", Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 更新任务详情UI
     */
    private void updateTaskDetailUI(TaskItem task) {
        titleTextView.setText(task.getTitle());
        contentTextView.setText(task.getContent());
        taskTypeTextView.setText("任务类型：" + task.getTaskType());
        statusTextView.setText(task.getStatus());
        priorityTextView.setText("优先级：" + task.getPriority());

        // 设置状态显示颜色
        if ("未开始".equals(task.getStatus())) {
            statusTextView.setTextColor(getResources().getColor(R.color.colorWarning));
        } else if ("进行中".equals(task.getStatus())) {
            statusTextView.setTextColor(getResources().getColor(R.color.colorPrimary));
        } else if ("已完成".equals(task.getStatus())) {
            statusTextView.setTextColor(getResources().getColor(R.color.colorSuccess));
        }

        // 设置时间信息
        if (task.getCreateTime() != null) {
            createTimeTextView.setText("创建时间：" + dateFormat.format(task.getCreateTime()));
        }

        if (task.getDeadline() != null) {
            deadlineTextView.setText("截止时间：" + dateFormat.format(task.getDeadline()));
        }

        // 设置创建者和接收者信息
        creatorTextView.setText("创建者：" + task.getCreatorId());
        assigneeTextView.setText("接收者：" + task.getAssigneeId());

        // 设置备注信息
        if (task.getRemark() != null && !task.getRemark().isEmpty()) {
            remarkTextView.setText("备注：" + task.getRemark());
        } else {
            remarkTextView.setVisibility(View.GONE);
        }

        // 设置附件信息
        if (task.isHasAttachment() && task.getAttachmentPath() != null) {
            attachmentTextView.setText("附件：" + task.getAttachmentPath());
        } else {
            attachmentTextView.setVisibility(View.GONE);
        }

        // 根据任务状态决定是否显示更新按钮
        if ("已完成".equals(task.getStatus())) {
            updateStatusContainer.setVisibility(View.GONE);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        // 刷新任务详情
        if (taskId != -1) {
            observeTaskDetail();
        }
    }
}